import { SuperMap3D } from '@/utils/supermap3d';
import { AnalysisContext, BaseAnalysis } from '@/utils/analysis/BaseAnalysis';

export interface ViewShedParams {
  direction?: number;
  pitch?: number;
  distance?: number;
  horizontalFov?: number;
  verticalFov?: number;
  visibleAreaColor?: string; // css颜色字符串
  hiddenAreaColor?: string; // css颜色字符串
}

export class ViewShedAnalysis extends BaseAnalysis {
  private viewShed: any;
  private pointHandler: any;
  private viewPosition: any = null;
  private isDrawing: boolean = false;
  // 参数初始值
  private params: Required<ViewShedParams> = {
    direction: 0,
    pitch: 0,
    distance: 1000,
    horizontalFov: 90,
    verticalFov: 60,
    visibleAreaColor: 'rgba(0, 255, 0, 1)', // 绿色半透明
    hiddenAreaColor: 'rgba(255, 0, 0, 1)', // 红色半透明
  };

  // constructor(ctx: AnalysisContext) {
  //   super(ctx);
  //   this.viewShed = new SuperMap3D.ViewShed3D(this.viewer.scene);
  //   this.pointHandler = new SuperMap3D.DrawHandler(this.viewer, SuperMap3D.DrawMode.Point);
  //   this.initEvents();
  // }

  constructor(ctx: AnalysisContext, params?: ViewShedParams) {
    super(ctx);
    if (params) {
      this.setParams(params);
    }
    this.viewShed = new SuperMap3D.ViewShed3D(this.viewer.scene);
    this.pointHandler = new SuperMap3D.DrawHandler(this.viewer, SuperMap3D.DrawMode.Point);
    this.initEvents();
  }

  public setParams(params: ViewShedParams) {
    this.params = {
      ...this.params,
      ...params,
    };
    console.log('[ViewShedAnalysis.setParams] 新参数:', this.params);
    if (this.viewShed) {
      this.applyParamsToViewShed();
      // console.log('[ViewShedAnalysis.setParams] 已调用applyParamsToViewShed和build', this.viewShed);
      this.viewShed.build();
    } else {
      // console.warn('[ViewShedAnalysis.setParams] this.viewShed为空，未能同步参数');
    }
  }

  private applyParamsToViewShed() {
    if (!this.viewShed) {
      // console.warn('[ViewShedAnalysis.applyParamsToViewShed] this.viewShed为空');
      return;
    }
    this.viewShed.direction = this.params.direction;
    this.viewShed.pitch = this.params.pitch;
    this.viewShed.distance = this.params.distance;
    this.viewShed.horizontalFov = this.params.horizontalFov;
    this.viewShed.verticalFov = this.params.verticalFov;
    this.viewShed.visibleAreaColor = SuperMap3D.Color.fromCssColorString(this.params.visibleAreaColor);
    this.viewShed.hiddenAreaColor = SuperMap3D.Color.fromCssColorString(this.params.hiddenAreaColor);
    // console.log('[ViewShedAnalysis.applyParamsToViewShed] 已同步到viewShed对象', {
    //   direction: this.viewShed.direction,
    //   pitch: this.viewShed.pitch,
    //   distance: this.viewShed.distance,
    //   horizontalFov: this.viewShed.horizontalFov,
    //   verticalFov: this.viewShed.verticalFov,
    //   visibleAreaColor: this.viewShed.visibleAreaColor,
    //   hiddenAreaColor: this.viewShed.hiddenAreaColor,
    // });
  }

  private initEvents(): void {
    // 移除之前的事件监听
    this.viewer.screenSpaceEventHandler.removeInputAction(SuperMap3D.ScreenSpaceEventType.MOUSE_MOVE);
    this.viewer.screenSpaceEventHandler.removeInputAction(SuperMap3D.ScreenSpaceEventType.RIGHT_CLICK);

    // 鼠标移动事件
    this.viewer.screenSpaceEventHandler.setInputAction((e: any) => {
      if (!this.isDrawing) return;

      const position = e.endPosition;
      const last = this.viewer.scene.pickPosition(position);

      if (last && this.viewPosition) {
        const distance = SuperMap3D.Cartesian3.distance(this.viewPosition, last);
        if (distance > 0) {
          const cartographic = SuperMap3D.Cartographic.fromCartesian(last);
          const longitude = SuperMap3D.Math.toDegrees(cartographic.longitude);
          const latitude = SuperMap3D.Math.toDegrees(cartographic.latitude);
          const height = cartographic.height;
          this.viewShed.setDistDirByPoint([longitude, latitude, height]);
        }
      }
    }, SuperMap3D.ScreenSpaceEventType.MOUSE_MOVE);

    // 右键点击事件
    this.viewer.screenSpaceEventHandler.setInputAction(() => {
      if (this.isDrawing) {
        this.isDrawing = false;
        // 这里可以触发属性面板显示
      }
    }, SuperMap3D.ScreenSpaceEventType.RIGHT_CLICK);

    // 点绘制事件
    this.pointHandler.drawEvt.addEventListener((result: any) => {
      // 设置点的大小 默认是10像素
      result.object.pixelSize = 5;
      // 得到点的位置
      const position = result.object.position;
      this.viewPosition = position;
      // 设置视口位置
      const cartographic = SuperMap3D.Cartographic.fromCartesian(position);
      const longitude = SuperMap3D.Math.toDegrees(cartographic.longitude);
      const latitude = SuperMap3D.Math.toDegrees(cartographic.latitude);
      const height = cartographic.height + 1.8; // 添加观察者高度

      // 设置视口位置
      this.viewShed.viewPosition = [longitude, latitude, height];
      // this.viewShed.distance = 1000;
      // this.viewShed.horizontalFov = 90;
      // this.viewShed.verticalFov = 60;
      // this.viewShed.direction = 0;
      // this.viewShed.pitch = 0;

      // 设置颜色 - 使用RGBA格式，alpha值设为0.3
      this.viewShed.visibleAreaColor = new SuperMap3D.Color(0.0, 1.0, 0.0, 0.3); // 绿色半透明
      this.viewShed.hiddenAreaColor = new SuperMap3D.Color(1.0, 0.0, 0.0, 0.3); // 红色半透明
      this.viewShed.hintLineColor = new SuperMap3D.Color(1.0, 1.0, 0.0, 1.0); // 黄色不透明
      this.isDrawing = true;
      // 构建可视域（空的可视域）
      this.viewShed.build();
    });
  }

  public activate(): void {
    this.clear();
    this.isDrawing = false;
    this.viewPosition = null;
    //可以禁用相机控制
    // this.viewer.scene.screenSpaceCameraController.enableRotate = false;
    // this.viewer.scene.screenSpaceCameraController.enableTranslate = false;
    // this.viewer.scene.screenSpaceCameraController.enableZoom = false;
    // this.viewer.scene.screenSpaceCameraController.enableTilt = false;

    // 激活点绘制
    this.pointHandler.activate();
  }

  // public activate(): void {
  //   this.clear();
  //   this.isDrawing = false;
  //   this.viewPosition = null;
  //   this.viewShed = new SuperMap3D.ViewShed3D(this.viewer.scene);
  //   this.pointHandler = new SuperMap3D.DrawHandler(this.viewer, SuperMap3D.DrawMode.Point);
  //   this.initEvents();
  //   this.pointHandler.activate();
  // }

  public clear(): void {
    // 重置状态
    this.isDrawing = false;
    this.viewPosition = null;
    // 恢复相机控制
    this.viewer.scene.screenSpaceCameraController.enableRotate = true;
    this.viewer.scene.screenSpaceCameraController.enableTranslate = true;
    this.viewer.scene.screenSpaceCameraController.enableZoom = true;
    this.viewer.scene.screenSpaceCameraController.enableTilt = true;

    // 清除点绘制
    if (this.pointHandler) {
      // this.pointHandler.deactivate();
      this.pointHandler.clear();
    }

    // 清除可视域
    if (this.viewShed) {
      // 移除所有裁剪区域
      this.viewShed.removeAllClipRegion();
      this.viewShed.clear();
      // 重置可视域参数
      // this.viewShed.viewPosition = null;
      // this.viewShed.distance = 0;
      // this.viewShed.horizontalFov = 0;
      // this.viewShed.verticalFov = 0;
      // this.viewShed.direction = 0;
      // this.viewShed.pitch = 0;
      // // 重新构建可视域（空的可视域）
      // this.viewShed.build();
    }
  }
}
